//
//  SearchPhotoViewController.swift
//  SwiftStudy
//
//  Created by wangyuxiang on 2018/2/5.
//  Copyright © 2018年 chang. All rights reserved.
//

import UIKit
import Alamofire
import SwiftyJSON
import SKPhotoBrowser
import GTMRefresh

class SearchPhotoViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate {

    var tableView : UITableView!
    var searchBar : UISearchBar!
    var dataArray = NSMutableArray()
    var currentPage: Int = 0
    var historyDataArray : NSMutableArray!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.defaultBackgroundColor
        
        tableView = UITableView.init(frame: self.view.bounds)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.separatorStyle = .none
        tableView.register(PictureTableViewCell.self, forCellReuseIdentifier: "pictureCell")
        self.view .addSubview(tableView)
        tableView.gtm_addRefreshHeaderView {
            [weak self] in
            self?.currentPage = 0
            self?.requestData()
        }
        tableView.gtm_addLoadMoreFooterView {
            [weak self] in
            self?.currentPage = (self?.currentPage)! + 1
            self?.requestData()
        }
        let headBgView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: self.view.width, height: 44))
        headBgView.backgroundColor = UIColor.defaultBackgroundColor
        tableView.tableHeaderView = headBgView
        
        searchBar = UISearchBar.init(frame: CGRect.init(x: 0, y: 0, width: headBgView.width - 100, height: headBgView.height))
        searchBar.delegate = self
        searchBar.placeholder = "输入\"美女\"有惊喜哦！"
        headBgView.addSubview(searchBar)
        
        let historyBtn = UIButton.init(type: .custom)
        historyBtn.frame = CGRect.init(x: searchBar.right, y: searchBar.top, width: 100, height: searchBar.height);
        historyBtn.backgroundColor = UIColor.clear
        historyBtn.setTitle("搜素历史", for: .normal)
        historyBtn.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        historyBtn.setTitleColor(UIColor.defaultYellowColor, for: .normal)
        historyBtn.addTarget(self, action: #selector(lookHistoryAction(sender:)), for: .touchUpInside)
        headBgView.addSubview(historyBtn)
        
        let hisArray = GetUserDefaults(key: SearchText_Keyword)
        if hisArray.isKind(of: NSArray.classForCoder()) && hisArray.count>0 {
            self.historyDataArray = NSMutableArray.init(array: hisArray as! NSArray)
        }else{
            self.historyDataArray = NSMutableArray.init(capacity: 0)
        }
    }
    
    // MARK: - UISearchBar
    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        searchBar.resignFirstResponder()
        
        let searchText : String = searchBar.text!
        if searchText.lengthOfBytes(using: .utf8)>0 {
            self.tableView.triggerRefreshing()
            //分线程去执行保存那些数据
            DispatchQueue.main.async {
                //第一次没有历史记录
                if self.historyDataArray.count == 0 {
                    self.historyDataArray.insert(searchText, at: 0)
                    SaveUserDefaults(key: SearchText_Keyword, value: self.historyDataArray.mutableCopy() as AnyObject)
                }else{
                    //判断是否有相同字段
                    var isEqual = false
                    for value in self.historyDataArray.enumerated() {
                        let valueStr : String = value.element as! String
                        if valueStr == searchText {
                            isEqual = true
                            break
                        }
                    }
                    if isEqual == false {
                        self.historyDataArray.insert(searchText, at: 0)
                        if self.historyDataArray.count>100 { //存放最新的100条数据
                            self.historyDataArray.removeLastObject()
                        }
                        SaveUserDefaults(key: SearchText_Keyword, value: self.historyDataArray.mutableCopy() as AnyObject)
                    }
                }
            }
        }
    }
    
    @objc func lookHistoryAction(sender: UIButton) {
        let searchHistoryVC = SearchHistoryViewController.init()
        searchHistoryVC.title = "搜索历史记录"
        searchHistoryVC.backCompletion = {
            [weak self]  (titleStr) in
            self?.searchBar.text = titleStr as String
            //这里不晓得为什么，需要延时之后才可以刷新changbo
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+0.2, execute: {
                self?.tableView.triggerRefreshing()
            })
        }
        self.navigationController?.pushViewController(searchHistoryVC, animated: true)
    }

    // MARK: - UITableView
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataArray.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let model: PictureModel = self.dataArray[indexPath.row] as! PictureModel
        return self.view.frame.size.width * 0.75 * (model.height / model.width) + 20
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell: PictureTableViewCell = tableView.dequeueReusableCell(withIdentifier: "pictureCell") as! PictureTableViewCell
        cell.selectionStyle = .none
        cell.refresh(model: self.dataArray[indexPath.row] as! PictureModel)
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        var images = [SKPhoto]()
        for index in 0..<self.dataArray.count {
            let model: PictureModel = self.dataArray[index] as! PictureModel
            let photo = SKPhoto.photoWithImageURL(model.url)
            photo.caption = model.desc
            photo.shouldCachePhotoURLImage = true
            images.append(photo)
        }
        
        SKPhotoBrowserOptions.displayBackAndForwardButton = false
        SKPhotoBrowserOptions.displayAction = false
        
        let browser = SKPhotoBrowser.init(photos: images)
        browser.initializePageIndex(indexPath.row)
        self.present(browser, animated: true, completion: nil)
    }
    
    // 请求数据
    func requestData() -> Void {
        self.view.makeToastActivity(.center)
        let text: String = searchBar.text!
        if text.isEmpty {
            self.tableView.endRefreshing(isSuccess: true)
            self.tableView.endLoadMore(isNoMoreData: false)
            return
        }
        
        if self.currentPage == 0 {
            dataArray.removeAllObjects()
        }
        
        //http://image.baidu.com/channel/listjson?pn=0&rn=20&tag1=美女
        let urlString = "http://image.baidu.com/channel/listjson?pn="+"\(self.currentPage * 20)"+"&rn=20&tag1=" + text
        let charSet = CharacterSet.init(charactersIn: urlString)
        let url = urlString.addingPercentEncoding(withAllowedCharacters: charSet)
        Alamofire.request(url!).responseJSON { response in
            self.view.hideToastActivity()
            //if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
                //print("Data: \(utf8Text)") // original server data as UTF8 string
            //}
            
            if let responseV = response.result.value {
                let json = JSON(responseV)
                let data = json["data"]
                for index in 0..<data.count {
                    let dic: Dictionary = data[index].dictionaryObject!
                    
                    if dic.count > 0 {
                        let model = PictureModel.init()
                        model.encode(dic: dic as [String : AnyObject])
                        self.dataArray.add(model)
                    }
                }
                self.tableView.reloadData()
            }
            
            self.tableView.endRefreshing(isSuccess: true)
            self.tableView.endLoadMore(isNoMoreData: false)
        }
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}
